package cc.magicjson.example.demo.spring.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class AppConfig {

    @Bean
    public BeanFactoryPostProcessor beanFactoryPostProcessor() {
        return beanFactory -> {
			if (beanFactory instanceof DefaultSingletonBeanRegistry) {
				try {
					Field singletonObjectsField = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
					singletonObjectsField.setAccessible(true);

					// 获取原始的 singletonObjects Map
					Map<String, Object> originalMap = (Map<String, Object>) singletonObjectsField.get(beanFactory);

					// 创建一个新的初始容量为 1024 的 ConcurrentHashMap
					Map<String, Object> newMap = new ConcurrentHashMap<>(1024);
					newMap.putAll(originalMap);

					// 将新的 Map 设置回 singletonObjects 字段
					singletonObjectsField.set(beanFactory, newMap);

					System.out.println("Original singletonObjects size: " + originalMap.size());
					System.out.println("New singletonObjects initial capacity: 1024");
				} catch (NoSuchFieldException | IllegalAccessException e) {
					throw new RuntimeException("Failed to modify singletonObjects field", e);
				}
			}
		};
    }
    
    // 示例 bean
    @Bean
    public String exampleBean() {
        return "example";
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        DefaultSingletonBeanRegistry beanRegistry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
        try {
            Field singletonObjectsField = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
            singletonObjectsField.setAccessible(true);
            Map<String, Object> singletonObjects = (Map<String, Object>) singletonObjectsField.get(beanRegistry);
            
            System.out.println("Final singletonObjects size: " + singletonObjects.size());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        
        context.close();
    }
}
